<?php
namespace app\admin\controller;

use app\common\BaseAdminController;
use app\common\Result;
use app\validate\Category as ValidateCategory;
use think\facade\Db;

class Category extends BaseAdminController
{
    public function list($pageNum = 1, $pageSize = 10)
    {
        // 分页查询所有分类
        $list  = Db::table('category')->page($pageNum, $pageSize)->select();
        $total = Db::table('category')->count(); // 获取总记录数

        return Result::success([
            'list'  => $list,
            'total' => $total,
        ], '查询成功');
    }

    public function add()
    {
        // 接收data
        $data = $this->request->post();
        // 验证数据
        $validate = new ValidateCategory();
        if (! $validate->check($data)) {
            return Result::error($validate->getError());
        }

        // 使用模型创建数据
        $category = new \app\model\Category();
        $result = $category->save($data);

        if ($result) {
            return Result::success(null, '添加成功');
        }

        return Result::error('添加失败');
    }

    public function update()
    {
        // 接收data
        $data = $this->request->post();
        // 验证数据
        $validate = new ValidateCategory();
        if (! $validate->check($data)) {
            return Result::error($validate->getError());
        }
        
        // 使用模型更新数据
        $category = \app\model\Category::find($data['id']);
        if (!$category) {
            return Result::error('分类不存在');
        }
        
        $result = $category->save($data);

        if ($result) {
            return Result::success(null, '更新成功');
        }

        return Result::error('更新失败');
    }
}
